package com.myebills.ebpsfrontend.cust.utils;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.myebills.ebpsfrontend.cust.controller.EbppxCusConstants;
import com.myebills.ebpsfrontend.cust.controller.EbppxCusDBUtil;





public class EmailNotification {
	
	  public static final String passphrase = "X2q3j5k6E7r8l93tm2n7H5qp";
	  public static final String emailProperty="config/emailDelivery.properties";
	  private Session mailSession;
	   
	  
	  
	  public String sendEmailNotification(String emailAddrs,String decrytionEmail,String acctNo,String decrytionAcctNo,String userId,String status,String accountName,String accountNameEncrypt,String emailLogAction,String channelID) throws MessagingException,AddressException,Exception {
			String strDate="";
			String action="";
			String actionStatus="";
		    String value="";
		    String messageId = "";
		    String strUserId="";
			strDate = DateUtil.formatDate(new Date());
			Connection connection = null;
			com.checkfree.isolutions.property.Properties appCfg = com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();
		 try{ 
			// Load the JDBC driver
	        connection = EbppxCusDBUtil.getDbConnection();
	        connection.setAutoCommit(false);
			EmailConfig emailConfig=new EmailConfig();
			
		
		    System.out.println("EMAIL :"+emailAddrs);
		    System.out.println("ACTION :"+emailLogAction);
			String subject="";
			String content="";
			String activationUrl="";
			
			
			

			emailConfig= getEmailSetting();
			
			//String emailEncrypt = EncryptionHelper.encrypt(emailAddrs,passphrase);
		    //String acctNoEncrypt = EncryptionHelper.encrypt(acctNo,passphrase);
	  
		    Message message = new MimeMessage(getSession(emailConfig));
			String EBPSHOST =appCfg.getProperty("EmailHost");
			String EBPSPATH =appCfg.getProperty("EmailPath");
			
			System.out.println("Host : "+EBPSHOST);
	        System.out.println("Path : "+EBPSPATH);
	        System.out.println("SUBSCRIPT :"+status);
	        System.out.println("email :"+emailAddrs);
	        System.out.println("decrytionEmail :"+decrytionEmail);
	      
	    
	    	
		    if(status.equalsIgnoreCase("subscript")){
			   subject=emailConfig.getSubscriptionSubject();
			   System.out.println("SUBJECT :"+subject);
			   //production activationUrl="https://"+EBPSHOST+"/"+EBPSPATH+"/CusEmailVerification_v1r00?email="+URLEncoder.encode(emailAddrs)+"&accounts="+URLEncoder.encode(acctNo)+"&name="+URLEncoder.encode(accountNameEncrypt);
			   activationUrl="https://"+EBPSHOST+"/"+EBPSPATH+"/CusEmailVerification_v1r00?email="+URLEncoder.encode(emailAddrs)+"&accounts="+URLEncoder.encode(acctNo)+"&name="+URLEncoder.encode(accountNameEncrypt);
			   if(emailLogAction.equalsIgnoreCase("update")){
				   
				   action = EbppxCusConstants.CUST_SUBSCRIPTION_UPDATE_ACTION;
				   actionStatus = EbppxCusConstants.CUST_SUBSCRIPTION_UPDATE_ACTION_VALUE;
			   
			   }else{
				   
				 action = EbppxCusConstants.CUST_SUBSCRIPTION_ACTION;
			     actionStatus = EbppxCusConstants.CUST_SUBSCRIPTION_ACTION_VALUE;
				   
			   }
			
			   strUserId=userId;
		 	   //content="Verify your email by clicking on the link below <h1>This is a test</h1><a href="+activationUrl+"></a><br/>"+activationUrl+"<br/><br/>if the link does not work , copy and paste the link to your browser window .";
			   //content="Verify your email by clicking on the link below <<br/>if the link does not work , copy and paste the link to your browser window .";
			   //content="<b>Dear Customer<b/><br/><br>Your E-bill registration is almost ready!</br><br>Take a minute to confirm this email address by clicking on the link below<form action="+activationUrl+" method=post><input type=submit style=background-color:#04B404; value=Yes,Register me for Maxis E-bill></form><br/><br>If you didnt 't sign up for Maxis E-bill,kindly disregard this message.</br><br>Someone probably typed in your email address by accident.</br><br>Thank you</br><br>Your Sincerely</br><br>Maxis</br></body>";
			   //content="Dear "+accountName+"<br/><br/><br/>Your E-bill registration is almost ready!<br/>Take a minute to confirm this email address by clicking on the link below .<br/><form action="+activationUrl+" method=post><input type=submit style=background-color:#04B404;color:white; value='Yes,Register me for Maxis E-bill'></form><br/>If you didnt 't sign up for Maxis E-bill,kindly disregard this message.<br/>Someone probably typed in your email address by accident.<br/>Thank you<br/><br/>Your Sincerely<br/>Maxis<br/></body>";
			   
			   //content="<body>Dear "+accountName+"<br/><br/><br/>Your E-bill registration is almost ready!<br/>Take a minute to confirm this email address by clicking on the link below .<br/><br/><a target=_blank style='padding:3px 10px;background-color:#04B404;color:white;text-decoration:none;' href="+activationUrl+">Yes,Register me for Maxis E-bill</a><br/><br/>If you didn't sign up for Maxis E-bill,kindly disregard this message.<br/>Someone probably typed in your email address by accident.<br/>Thank you<br/><br/>Yours Sincerely<br/>Maxis<br/></body>";
			   //content="<body><span style='font-family: arial;'>Dear "+accountName+"<br/><br/><br/>Your E-bill registration is almost ready!<br/>Take a minute to confirm this email address by clicking on the link below .<br/><br/><a target=_blank style='padding:3px 10px;background-color:#04B404;color:white;text-decoration:none;' href="+activationUrl+">Yes,Register me for Maxis E-bill</a><br/><br/>If you didn't sign up for Maxis E-bill,kindly disregard this message.<br/>Someone probably typed in your email address by accident.<br/>Thank you<br/><br/>Yours Sincerely<br/>Maxis<br/></span></body>";
			   content="<body><span style='font-family:arial;'>Dear "+accountName+",<br/><br/><br/>Your E-bill registration is almost ready!<br/><br/>Take a minute to confirm this email address by clicking on the link below:<br/><br/><a target=_blank style='padding:3px 10px;background-color:#04B404;color:white;text-decoration:none;' href="+activationUrl+" onmouseover='window.status='';return true'>Yes, Register me for Maxis E-bill</a><br/><br/>If you didn't sign up for Maxis E-bill, kindly disregard this message.<br/>Someone probably typed in your email address by accident.<br/><br/> Thank you.<br/><br/>Yours sincerely,<br/>Maxis<br/></span></body>";
			   
		    }
		   
		    if(status.equalsIgnoreCase("unsubscription")){
			   subject=emailConfig.getUnsubscriptionSubject();
			   System.out.println("SUBJECT :"+subject);
			   content="<body><span style='font-family: arial;'>Dear "+accountName+",<br/><br/>You have requested to cancel Maxis E-bill service.<br/><br/>Please tweet us at @MaxisListens should you require further assistance.<br/><br/>Thank you.<br/><br/>Yours sincerely,<br/>Maxis<br/></span></body>";
			   action = EbppxCusConstants.CUST_UNSUBSCRIPTION_ACTION;
			   actionStatus = EbppxCusConstants.CUST_UNSUBSCRIPTION_ACTION_VALUE;
		   
			   strUserId=userId;
			       
			      	
		    }
			if(status.equalsIgnoreCase("success")){
			   subject=emailConfig.getSucessfulSubject();
			      content="<body><span style='font-family: arial;'>Dear "+accountName+",<br/><br/>Thank you for signing up Maxis E-bill service.You will also enjoy the RM5 rebate of itemised billing service starting in your next month bill.<br/><br/>Please tweet us at @MaxisListens should you require further assistance.<br/><br/>Thank you.<br/><br/>Yours sincerely,<br/>Maxis<br/></span></body>";
			   action = EbppxCusConstants.CUST_VERIFICATION_ACTION;
			   actionStatus = EbppxCusConstants.CUST_VERIFICATION_ACTION_ACTION;
			   System.out.println(content);
			}
			if(strUserId.equals("")){
				strUserId="USER";
			}
		  
		    System.out.println("Content :"+content);
		    System.out.println("Subject :"+subject);
		    message.addRecipient(RecipientType.TO, new InternetAddress(decrytionEmail));
		    message.setFrom(new InternetAddress(emailConfig.getSenderAddr()));
		    message.setSubject(subject);
		    message.setContent(content, "text/html; charset=ISO-8859-1");
		    message.setSentDate(new Date());

		    Transport.send(message);
		    //messageId= "1";
		    messageId = message.getHeader("Message-ID")[0];
			System.out.println("MESSAGE :"+messageId.toString());
			EbppxCusDBUtil.logEmailDelivery(connection,decrytionAcctNo, decrytionEmail,strDate,strUserId, action, actionStatus,channelID);
			connection.commit();//ebps
			connection.setAutoCommit(true);

			System.out.println("Done");
	        
		 }catch(MessagingException e){
			 strDate = DateUtil.formatDate(new Date());
			 EbppxCusDBUtil.logEmailDelivery(connection,decrytionAcctNo, decrytionEmail,strDate, strUserId, action,"Email Sent Failed",channelID);
		     e.printStackTrace();
		
			
		 }catch(Exception e){
			 EbppxCusDBUtil.logEmailDelivery(connection,decrytionAcctNo,decrytionEmail,strDate, strUserId, action, "Email Sent Failed",channelID);
			 e.printStackTrace();
		     return messageId;
		 }finally {
			 connection.commit();//ebps
			 connection.setAutoCommit(true);

		      try {
				connection.rollback();
				 
		    
		        if (connection!=null){
		          EbppxCusDBUtil.freeDbConnection(connection);
		        }
		      
		      }catch (SQLException e1) {
					System.out.println("Exception1 is:"+e1);
		        throw new ServletException(e1);
		      }catch (Throwable t1){
					System.out.println("Throwable1 is:"+t1);
		        throw new ServletException(t1.toString(), t1);
		      }
		    }
		    
	    System.out.println("MESSAGE ID :"+messageId);
		return messageId;
	
	       
		 }    
					
			
		
		
		public  EmailConfig getEmailSetting() throws IOException{
			
			//InputStream input =null;
			EmailConfig EmailConfig=new EmailConfig();
				
			try {
			
				 Properties properties = new Properties();
				 properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(emailProperty));
				
				//EmailConstant email;
				EmailConfig.setSmtpHost(properties.getProperty("email.smtp.host"));
			    EmailConfig.setSmtpPort(properties.getProperty("email.smtp.port"));
			    EmailConfig.setUserName(properties.getProperty("email.user.name"));
		        EmailConfig.setPassword(properties.getProperty("email.user.password"));
		        EmailConfig.setSenderAddr(properties.getProperty("email.send.senderAddress"));
		        EmailConfig.setSucessfulSubject(properties.getProperty("email.send.successful.subject"));
		        EmailConfig.setSubscriptionSubject(properties.getProperty("email.send.emailsubscript.subject"));
		        EmailConfig.setUnsubscriptionSubject(properties.getProperty("email.send.emailunsubscript.subject"));
			
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch(IOException ex) {
				ex.printStackTrace();
			} 			
				
			return EmailConfig;
			
			
			
		}

		
		private Session getSession(EmailConfig emailConfigDTO) throws MessagingException {
			
			
			Authenticator authenticator = new Authenticator(emailConfigDTO);
			

			Properties properties = new Properties();
			properties.setProperty("mail.smtp.starttls.enable", "true");
			properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
			properties.setProperty("mail.smtp.auth", "true");
			properties.setProperty("mail.smtp.auth.mechanisms","NTLM");
			properties.setProperty("mail.smtp.host", emailConfigDTO.getSmtpHost());
			System.out.println("HOST :"+emailConfigDTO.getSmtpHost());
			properties.setProperty("mail.smtp.port", emailConfigDTO.getSmtpPort());
			
			return Session.getInstance(properties, authenticator);
		}

		private class Authenticator extends javax.mail.Authenticator {
			private PasswordAuthentication authentication;

			public Authenticator(EmailConfig emailConfig) {
				String username = emailConfig.getUserName();
				String password = emailConfig.getPassword();
				authentication = new PasswordAuthentication(username, password);
			}

			protected PasswordAuthentication getPasswordAuthentication() {
				return authentication;
			}
		}
		
		
		public static void main(String[] a) throws MessagingException{
			EmailNotification ab=new EmailNotification();
	      
		}

	

		

}
